﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ShrinkWrap.HttpHandler
{
    public class CompositeUri : Uri
    {
        char[] constituentDelimiter = new char[] { '+' };
        char[] extensionDelimiter = new char[] { '.' };

        public CompositeUri(Uri uri)
            : this(uri.OriginalString)
        {
        }

        public CompositeUri(String uriString)
            : base(uriString)
        {
        }

        public IEnumerable<Uri> ConstituentUris
        {
            get
            {
                // Remove the bundle from the end of the URI to get the stem
                String wholeUri = ToString();
                int nonStemLength = filenameBundle.Length + Query.Length;
                String stem = wholeUri.Remove(wholeUri.Length - nonStemLength);

                // Use the stem to build a Uri from each filename
                return fileNames.Select(filename => new Uri(stem + filename + Query));
            }
        }

        IEnumerable<String> fileNames
        {
            get
            {
                return filenameBundle.Split(constituentDelimiter);
            }
        }

        String filenameBundle
        {
            get
            {
                return Segments.Last();
            }
        }

        public bool HasDifferingFileExtensions
        {
            get
            {
                // Check whether all extensions are equal to the last i.e. they all the same
                IEnumerable<String> extensions = fileNames.Select<String, String>(getExtension);
                bool allTheSame = extensions.All(extension => extension == extensions.First());

                return !allTheSame;
            }
        }

        String getExtension(String filename)
        {
            String[] parts = filename.Split(extensionDelimiter);

            if (parts.Length == 1)
            {
                // If there isn't more than one part there is no file extension
                return "";
            }
            else
            {
                // Take the last rather than the second part in case there are multiple '.'s in filename
                return parts.Last();
            }
        }
    }
}
